define(['config', 'wrapper', 'ztree',
	'text!app/module/system/orgstructure.html', 'jqGrid', 'common',
	'css!app/assets/lib/ztree/css/demo.css',
	'css!app/assets/lib/ztree/css/zTreeStyle/zTreeStyle.css', "mydialog", "inc"
], function (
	config, wrapper, ztree, viewHTML, jqGrid, common, mydialog, inc) {
	var grid_url = "/api/depart/bylistdepartid";
	var token = (cache.go("token") === 'undefined') ? 'none' : cache
		.go("token");
	var model = avalon.define({
		$id: 'orgstructure',
		query: {
			id: "",
			keyword: ""
		},
		info: [],
		departLevelValue: [{
			key: "1",
			val: "1"
		}, {
			key: "2",
			val: "2"
		}, {
			key: "3",
			val: "3"
		}],
		depart: {
			id: "",
			departID: "", //
			parentID: 0,
			deptLevel_NR: 0, // 级别 departLevel
			departName: "", // 组织结构名称
			socialCode: "",
			memo_TX: "", // 组织机构简称 memo
			tagName: "", // 索引码
			departCD: "", // 企业代码
			prefix: "", // 面单前缀
			departType: "1" // 企业类型
		},
		dpeartParentName: "",
		init: function () {
			//一进页面初始化ztree菜单模块
			model.loadZTree();
			model.addEvent();
		},
		loadZTree: function () {
			var url = "/api/depart/byid?id=0";
			var orgZTree; // 定义全局ZTree对象，存放整个生成的Ztree树
			var orgSetting = { // 生成树结构时的setting属性
				isSimpleData: true, // 制定可以支持数据结构，不用转换为复杂的josn对象
				showIcon: false, // 不显示图标
				treeNodeKey: "id", // 如指定isSimpleDate:true,这个属性必须被指定
				treeNodeParentKey: "parentId", // 如指定isSimpleDate:true,这个属性必须被指定
				showLine: true, // 显示父子之间的线
				data: {
					keep: {
						parent: true
					}
				},
				checkStyle: "checkbox", // check组件类型为checkbox
				checkRadioType: "all",
				callback: { // 回调函数
					beforeClick: zTreeBeforeClick,
					beforeExpand: zTreeBeforeExpand,

				}
			};
			/**
			 * url:url地址
			 * type:dataType类型
			 * successfn:成功时回调
			 * errorfn：错误回调
			 * ajax 封装
			 * 
			 */
			function AjaxMethod(url, type, successfn, errorfn) {
				$.ajax({
					url: url,
					dataType: type,
					beforeSend: function (jqXHR) {
						jqXHR.setRequestHeader("X-AuthToken", token);
					},
					success: function (e) {
						successfn(e);
					},
					error: function (e) {
						errorfn(e);
					}
				});
			}

			//抽取折叠和点击事件监听处理
			function g(treeId, treeNode) {
				url = "/api/depart/byid?id=" + treeNode.id
				//给右侧表格传当前选择ID并加载表格数据
				model.query.id = treeNode.id;
				model.query.keyword = "";
				model.searchInfo();
				//给级别还有上级机构名称赋值  
				model.depart.deptLevel_NR = treeNode.level + 1;
				model.depart.parentID = treeNode.id;
				model.dpeartParentName = treeNode.name;
				//判断 当前节点下是否已经加载过数据如果没有则查询加载子菜单
				if (typeof (treeNode.children) == "undefined") {
					// 发送ajax 动态获取子菜单
					AjaxMethod(url, "json", function (data) {
						var orgZTree = $.fn.zTree.getZTreeObj("orgTree"); // 获取ztree对象
						var parentZNode = orgZTree.getNodeByParam("id",
							treeNode.id, null); // 获取父节点
						orgZTree.addNodes(parentZNode, -1, data, false);
					});
				}
			}
			// 页面一加载的时候 发送请求 查询 父节点菜单
			AjaxMethod(url, "json", function (data) {
				orgZTree = $.fn.zTree.init($("#orgTree"), orgSetting, data);
				//加载右侧表格数据
				model.loadGrid();
			})


			// ztree 监听展开折叠 事件
			function zTreeBeforeExpand(treeId, treeNode) {
				g(treeId, treeNode)
				return true;
			};
			// ztree 监听点击事件 事件
			function zTreeBeforeClick(treeId, treeNode, clickFlag) {
				g(treeId, treeNode)
			};

		},
		loadGrid: function () {
			var i = Public.setGrid();

			function t(val, opt, row) {
				var html_con = '<div class="operating" data-id="' + row.id + '"><span class="fa fa-edit mrb" title="修改"><a href="javascript:void();" ms-click="edit(el)"/></span><span class="fa fa-trash-o mrb" title="删除"></span>' + (row.is_deleted == 1 ? '<span class="fa fa-reply mrb" title="恢复"></span>' : '') + '</div>';
				return html_con;
			}
			$("#jqgrid_table").jqGrid({
				loadBeforeSend: function (jqXHR) {
					jqXHR.setRequestHeader("X-AuthToken", token);
				},
				url: grid_url,
				datatype: "json",
				postData: model.query,
				colModel: [{
						name: 'operating',
						label: '操作',
						width: '10%',
						formatter: t,
						align: 'center',
						title: false
					},
					{
						name: 'id',
						label: "id",
						width: '5%',
						align: 'center',
						title: false,
						hidden: true
					},
					{
						name: 'departType',
						label: 'departType',
						width: '5%',
						align: 'center',
						title: false,
						hidden: true
					},
					{
						name: 'departID',
						label: '编号',
						width: '5%',
						align: 'center',
						title: false
					},
					{
						name: 'departName',
						label: '组织名称',
						width: '15%',
						align: 'center',
						title: false
					},
					{
						name: 'departCD',
						label: '企业代码',
						width: '15%',
						align: 'center',
						title: false
					},
					{
						name: 'memo_TX',
						label: '组织简称',
						width: '20%',
						align: 'center',
						title: false
					},
					{
						name: 'tagName',
						label: '索引名称',
						width: '10%',
						align: 'center',
						title: false
					},
					{
						name: 'prefix',
						label: '面单前缀',
						width: '10%',
						align: 'center',
						title: false
					},
					{
						name: 'socialCode',
						label: '社会统一信用代码',
						width: '15%',
						align: 'center',
						title: false
					}
				],
				cmTemplate: {
					sortable: false,
					title: false
				},
				page: 1,
				rowNum: 20,
				rowList: [10, 20, 30],
				height: i.h,
				autowidth: true,
				pager: '#page',
				sortname: 'id',
				viewrecords: true,
				forceFit: false,
				rownumbers: true,
				multiselect: true,
				multiboxonly: true,
				sortorder: "desc",
				jsonReader: {
					root: "data.list",
					records: "data.totalRow",
					total: "data.totalPage",
					repeatitems: false,
					id: "id"
				}
			}) // jqGrid End
		}, // grid End
		del: function (ids, dertptIds) {
			dialog({
				title: "确认操作",
				content: "确定删除？ 此操作不可恢复！",
				okValue: "确定",
				ok: function () {
					$.ajax({
						type: "POST",
						url: "/api/depart/del",
						data: {
							"ids": ids,
							"dertptIds": dertptIds
						},
						beforeSend: function (xhr) {
							xhr.setRequestHeader("X-AuthToken", token);
						},
						success: function (data, status, xhr) {
							if (data) {
								model.searchInfo();
							} else {
								alert("不能删除")
							}
						},
						error: function (responseData, textStatus, errorThrown) {
							alert("Failed: " + responseData);
						}

					});

				},
				cancelValue: "取消",
				cancel: function () {}
			}).showModal();
		},
		edit: function (depart) {
			if (depart === -1) {
				//如果等于-1则是新建需要赋空属性值
				model.depart.id = "";
				model.depart.departName = ""; // 组织结构名称
				model.depart.memo_TX = ""; // 组织机构简称 memo
				model.depart.tagName = ""; // 索引码
				model.depart.departCD = ""; // 企业代码
				model.depart.prefix = ""; // 面单前缀
				model.depart.departType = "2"; // 企业类型
				model.depart.socialCode = "";
				model.depart.socialCode = "";
				model.depart.departID = null;
				model.depart.departNo = null;
				model.depart.telNo = "";
				model.depart.parentList_TX = "";
				model.depart.deptNature_CD = "";
				model.depart.cost = 0;
			} else {
				//不等于-1则是修改
				// model.depart=depart;
			}
			var departDialog = dialog({
				title: '新增/编辑组织结构',
				content: $('#AddDepart'),
				id: 'EF893L1',
				okValue: '确定',
				ok: function () {
					$.ajax({
						url: "api/depart/addorupdDepart",
						type: "POST",
						contentType: "application/json", // 必须有
						dataType: "json", // 表示返回值类型，不必须
						data: JSON.stringify(model.depart.$model),
						beforeSend: function (xhr) {
							xhr.setRequestHeader("X-AuthToken", token);
						},
						success: function (data, status, xhr) {
							successDialog().showModal();
							model.searchInfo();


						},
						error: function (data) {
							errorDialog(data).showModal();
						}
					});
				},
				cancelValue: '取消',
				cancel: function () {},
				onclose: function () {
					// 取消按钮和关闭按钮都走此方法
					departDialog.remove();
					//  $("#AddDepart input[type='text'],input[type='hidden'],textarea").val("");
					//  $("#AddDepart select").val("");
				}
			}).showModal();
		},
		addEvent: function () {
			var t = this;
			$(".grid-wrap").on("click", ".fa-edit", function (e) {
				id = $("#jqgrid_table").jqGrid('getGridParam', 'selrow'),
					dapartId = $("#jqgrid_table").jqGrid("getRowData", id).departID;
				model.getDepart(dapartId);
				model.edit();
			});
			// 删除
			$(".grid-wrap").on("click", ".fa-trash-o", function (t) {
				var ei = [];
				var e = $(this).parent().data("id");
				var f = $("#jqgrid_table").getRowData(e).departID;
				model.del(e, f);
			});
			$("#btn-batchDel").click(function (e) {
				e.preventDefault();
				var t = $("#jqgrid_table").jqGrid("getGridParam", "selarrrow");
				var ids = $("#jqgrid_table").jqGrid('getDataIDs');
				var arr = [];
				for (var i = 0; i < ids.length; i++) {
					arr.push($("#jqgrid_table").jqGrid('getCell', ids[i], "departID"));
				}
				t.length ? model.del(t.join(), arr.join()) : parent.Public.tips({
					type: 2,
					content: "请选择需要删除的项"
				})
			});
		},
		searchInfo: function () {
			// 搜索
			model.loadInfo();

		}, // search function End
		reset: function () {
			// 重置搜索条件
			model.query.keyword = "";
			model.loadInfo();

		}, // reset function End
		loadInfo: function () {
			// 重新加载数据
			$("#jqgrid_table").jqGrid("setGridParam", {
				url: "/api/depart/bylistdepartid",
				datatype: "json",
				type: 'POST',
				postData: model.query.$model
			}).trigger("reloadGrid");

		}, // loadModel function End
		getDepart: function (id) {
			debugger;
			Public.ajaxGet("/api/depart/bydepartid", {
				"id": id
			}, token, function (data) {
				model.depart = data.data
			})
		}
	})

	// 定义视图模块
	var viewmod = {
		viewtSrc: viewHTML,
		viewInit: function () {
			model.init();
		}, // 模块view加载完成后的回调方法，在刷新（F5）时可能调用两次
		viewDestroy: function () {} // 切换菜单时销毁原来的view
	};
	return viewmod;
});